import styles from "./root.module.css";
import Header from "@/pages/root/header.jsx";
import CustomerMenu from "@/pages/root/menu.jsx";
import MainContent from "@/pages/root/main-content.jsx";
import { useMatches, useNavigate } from "react-router-dom";
import { isEmpty, last } from "wsp-toolkit";
import { useEffect } from "react";
import { StorageKey } from "@/enums/dictionaries.js";
import { getAuthMenu, getUserInfo, isAdmin } from "@/utils";

export default function Root() {
  const navigate = useNavigate();
  const matches = useMatches();
  const pathName = last(matches).pathname;

  useEffect(() => {
    if (pathName === "/login") {
      return;
    }
    if (isEmpty(localStorage.getItem(StorageKey.token))) {
      navigate("/login", {
        replace: true,
      });
      return;
    }
    if (isAdmin()) {
      return;
    }
    if (!getAuthMenu().includes(pathName)) {
      navigate("/error/access-denied");
    }
  }, [pathName]);

  return (
    <div className={styles.root}>
      <Header />
      <div className={styles.main}>
        <CustomerMenu />
        <MainContent />
      </div>
    </div>
  );
}
